require('express-async-errors')
const createError = require('http-errors')
const express = require('express')
const session = require('express-session')
const path = require('path')
const cookieParser = require('cookie-parser')
const logger = require('morgan')

const loginRouter = require('./routes/login')
const adminRouter = require('./routes/admin')
const applicationRouter = require('./routes/application')
const recruitRouter = require('./routes/recruit')

const app = express()

index.set('views', path.join(__dirname, 'views'))
index.set('view engine', 'pug')

index.all('*', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*') //任意一个源都可访问
  res.header('Access-Control-Allow-Headers', '*') //任意的头都可以访问
  res.header('Access-Control-Allow-Methods', '*') //任意的请求类型都可以访问
  if (req.method.toLowerCase() == 'options') res.sendStatus(200)
  else next()
})

index.set('views', path.join(__dirname, 'views'))
index.set('view engine', 'jade')

index.use(logger('dev'))
index.use(express.json())
index.use(express.urlencoded({ extended: false }))
index.use(cookieParser())

index.use('/public', express.static(path.join(__dirname, 'public')))

index.use('/',loginRouter)
index.use('/admin', adminRouter)
index.use('/application', applicationRouter)
index.use('/recruit', recruitRouter)

index.use(function (err, req, res, next) {
  console.log(`[全局异常捕获]${err.message}`)
  console.log(err)
  res.header('Content-Type', 'application/text; charset=utf-8')
  res.status(err.status || 500).send(err.message)
})

global.tokenKey = '123456'

global.throw = msg => {
  throw new Error(msg)
}

module.exports = index;
